package chances.wechat.service.rdb;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import chances.wechat.api.TokenSet;
import chances.wechat.service.WechatTokenService;

@Service("tokenService")
public class RdbWechatTokenService extends BaseDao implements WechatTokenService {

	public void saveWechatToken(TokenSet token) {
		if(this.isExist(token.getAppId())) {
			this.updateWechatToken(token);
		} else {
			this.insertWechatToken(token);
		}
	}

	@Override
	public TokenSet getWechatTokenByAppId(String appId) {
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("appId", appId);
		try {
			return (TokenSet) this.queryForObject("getWechatTokenByAppId", paramsMap);
		} finally {
			paramsMap.clear();
			paramsMap = null;
		}
	}

	public boolean isExist(String appId) {
		TokenSet tokenSet = this.getWechatTokenByAppId(appId);
		if(tokenSet != null) {
			return true;
		}
		return false;
	}

	@Override
	public void insertWechatToken(TokenSet token) {
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("obj", token);
		try {
			this.insert("insertWechatToken", paramsMap);
		} finally {
			paramsMap.clear();
			paramsMap = null;
		}
	}

	@Override
	public void updateWechatToken(TokenSet token) {
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("obj", token);
		try {
			this.update("updateWechatToken", paramsMap);
		} finally {
			paramsMap.clear();
			paramsMap = null;
		}
	}

	@Override
	public List<TokenSet> getAllWechatToken() {
		List<TokenSet> result = (List<TokenSet>) this.queryForList("getAllWechatToken");
		return result;
	}

}
